package com.it.schoolhomeos.controller;

import com.it.schoolhomeos.dto.UserDTO;
import com.it.schoolhomeos.entity.User;
import com.it.schoolhomeos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "提供用户个人信息管理功能")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "获取个人信息", description = "获取当前登录用户的个人信息")
    public ResponseEntity<UserDTO> getProfile() {
        return ResponseEntity.ok(userService.getCurrentUser());
    }

    @PutMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "更新个人信息", description = "更新当前登录用户的个人信息")
    public ResponseEntity<UserDTO> updateProfile(@Parameter(description = "用户信息") @RequestBody User user) {
        return ResponseEntity.ok(userService.updateProfile(user));
    }

    @PutMapping("/password")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "修改密码", description = "修改当前登录用户的密码")
    public ResponseEntity<Map<String, String>> changePassword(
            @Parameter(description = "密码信息") @RequestBody Map<String, String> passwordInfo) {
        try {
            String oldPassword = passwordInfo.get("oldPassword");
            String newPassword = passwordInfo.get("newPassword");
            
            if (oldPassword == null || newPassword == null) {
                return ResponseEntity.badRequest().body(Map.of("message", "旧密码和新密码不能为空"));
            }
            
            userService.changePassword(oldPassword, newPassword);
            
            return ResponseEntity.ok(Map.of("message", "密码修改成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("message", "密码修改失败: " + e.getMessage()));
        }
    }

    @PutMapping("/avatar")
    @PreAuthorize("isAuthenticated()")
    @Operation(summary = "更新头像", description = "更新当前登录用户的头像")
    public ResponseEntity<Map<String, String>> updateAvatar(
            @Parameter(description = "头像URL") @RequestBody Map<String, String> avatarInfo) {
        String avatarUrl = avatarInfo.get("avatarUrl");
        
        userService.updateAvatar(avatarUrl);
        
        return ResponseEntity.ok(Map.of("message", "头像更新成功"));
    }
} 